<template>
  <div class="user-manage">
    <!-- 顶部操作区域 -->
    <div class="toolbar">
      <h2 class="section-title">用户管理</h2>

      <!-- 搜索框和搜索按钮 -->
      <div class="search-bar">
        <input
          v-model="searchKeyword"
          type="text"
          placeholder="请输入用户名"
          @keyup.enter="handleSearch"
        />
        <button @click="handleSearch" class="blue-btn search-btn">搜索</button>
      </div>
    </div>

    <!-- 表格区域，带滚动容器 -->
    <div class="user-table-wrapper" ref="scrollContainer">
      <table class="user-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>权限</th>
            <th class="action-column">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.email }}</td>
            <td>{{ formatPower(user.power) }}</td>
            <td class="action-column">
              <div class="action-buttons">
                <button @click="deleteUser(user.id)" class="blue-btn">删除</button>
              </div>
            </td>
          </tr>
          <tr v-if="users.length === 0 && !isLoading">
            <td colspan="5" style="text-align: center; color: #888">暂无数据</td>
          </tr>
        </tbody>
      </table>

      <!-- 加载提示 -->
      <div v-if="isLoading" class="loading-indicator">加载中...</div>
      <div v-if="finished && users.length > 0" class="loading-indicator">没有更多数据了</div>
    </div>

    <!-- 弹窗组件 -->
    <MyDialog ref="dialogRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'
import MyDialog from './MyDialog.vue' // 根据实际路径调整

interface User {
  id: number
  username: string
  email: string
  power: number // 权限数字
}

const users = ref<User[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = 20
const searchKeyword = ref('')
const isLoading = ref(false)
const finished = ref(false)

// 弹窗组件 ref
const dialogRef = ref<InstanceType<typeof MyDialog>>()

// 格式化权限显示
const formatPower = (power: number): string => {
  return power === 1 ? '普通用户' : power > 1 ? '管理员' : '未知权限'
}

// 加载用户数据
const fetchData = async (reset = false) => {
  if (isLoading.value) return
  if (reset) {
    page.value = 1
    users.value = []
    finished.value = false
  }

  isLoading.value = true
  try {
    const res = await axios.get('/api/userManagement/search', {
      params: {
        keyword: searchKeyword.value.trim(),
        page: page.value,
        size: pageSize,
      },
    })

    const data = res.data
    if (data.data && data.data.length > 0) {
      if (reset) {
        users.value = data.data
      } else {
        users.value.push(...data.data)
      }
      total.value = data.total
      page.value++
    } else {
      finished.value = true
    }
  } catch (error) {
    console.error('加载失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 删除用户
const deleteUser = async (id: number) => {
  const confirm = await dialogRef.value?.open('确定删除该用户吗？', true)
  if (!confirm) return

  try {
    const res = await axios.delete(`/api/userManagement/delete/${id}`)
    if (res.data.success) {
      fetchData(true)
    } else {
      await dialogRef.value?.open(res.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除请求失败:', error)
    await dialogRef.value?.open('该用户存在未归还图书')
  }
}

const handleSearch = () => {
  fetchData(true)
}

const scrollContainer = ref<HTMLElement | null>(null)

const onScroll = () => {
  if (!scrollContainer.value) return
  const el = scrollContainer.value
  const scrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight
  if (scrollBottom < 50 && !isLoading.value && !finished.value) {
    fetchData()
  }
}

onMounted(() => {
  fetchData()
  if (scrollContainer.value) {
    scrollContainer.value.addEventListener('scroll', onScroll)
  }
})

onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener('scroll', onScroll)
  }
})
</script>

<style scoped>
.user-manage {
  padding: 0 20px;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 5px;
}

.search-bar {
  display: flex;
  gap: 8px;
}

.search-bar input {
  padding: 6px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 200px;
}

.blue-btn {
  padding: 6px 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  min-width: 80px;
  user-select: none;
}

.blue-btn:hover {
  background-color: #66b1ff;
}

.user-table-wrapper {
  max-height: 620px;
  overflow-y: auto;
  border: 1px solid #ccc;
  margin-bottom: 20px;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th,
.user-table td {
  border: 1px solid #ccc;
  padding: 12px;
  text-align: left;
}

.user-table th {
  background-color: #f5f5f5;
}

.action-column {
  width: 140px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.loading-indicator {
  text-align: center;
  color: #888;
  margin: 10px 0;
}

.search-btn {
  user-select: none;
}
</style>
